package com.hsmpay.mobile.action.account.fc;

import com.hsmpay.common.pojo.qian4.Qian4SendLog;
import com.hsmpay.common.pojo.user.User;
import com.hsmpay.common.util.DateConvertUtil;
import com.hsmpay.common.util.OrderTypeUtil;
import com.hsmpay.common.util.URLDecoderTools;
import com.hsmpay.mobile.action.account.qian48.Q4BaseAction;
import com.hsmpay.mobile.pojo.terminal.Tchannel;
import com.hsmpay.mobile.pojo.trans.TransOrder;
import com.hsmpay.mobile.pojo.trans.TransPriorSettle;
import com.hsmpay.mobile.service.trans.TransPriorSettleService;
import com.hsmpay.mobile.util.icc.ME30DataDecode;
import com.hsmpay.utils.Des3;
import com.test.JDPushConfig;
import com.test.JdPush;
import it.sauronsoftware.base64.Base64;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.hsmpay.qian4.pojo.PurchaseResult;
import com.hsmpay.utils.TimeUtils;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class PurchaseBaseAction extends Q4BaseAction {
    private static final long serialVersionUID = 4841990981226162770L;
    private static Logger log = Logger.getLogger(PurchaseBaseAction.class);

    @Resource(name = "transPriorSettleService")
    public TransPriorSettleService<TransPriorSettle, Long> transPriorSettleService;

    public final static int TC_ECB = 33;//ECB
    public final static int TC_RuiSheng = 34;//瑞晟
    public final static int TC_ZHONGYI = 36;//中亿
    public final static int TC_RuiSheng_GT = 38;//瑞晟国通
    public final static int TC_Uinpay  = 43;//u银支付
    public final static int TC_YinShengBao = 52;//银生宝
    public final static int TC_POSP = 51;//POSP
    public final static int TC_POS = 54;//POS
    public final static int TC_EPOINT = 40;//E点
    public final static int TC_GUOTONG = 41;//国通
    public final static int TC_ZHIFUTONG = 57;//支付通
    public final static int TC_HANXIN = 58;//翰鑫
    public final static int TC_ZHONGLAN = 81;//中岚
    public final static int TC_KAYINKA = 65;//卡银卡

    protected Object[] assembleBean(User user) throws Exception {
        log.debug("--- receivablesToCard() start ---");
        clientType = Integer.parseInt(getJsonString("clientType"));
        terminalTypeId = Long.parseLong(getJsonString("terminalTypeId"));
        roleId = Long.parseLong(getJsonString("roleId"));

        functionKey = getJsonString("functionKey");
        merchantOrderId = getJsonString("merchantOrderId").substring(0,17).toString();
        merchantOrderTime = getJsonString("merchantOrderTime");
        terminalId = getJsonString("terminalId");
        transAmt = getJsonString("transAmt");
        accountNumber = getJsonString("accountNumber");
        pin = getJsonString("pin");
        track2Data = getJsonString("track2Data");
        track3Data = getJsonString("track3Data");
        cardholderSign = getJsonString("cardholderSign");
        dynamicKeyData = getJsonString("dynamicKeyData");
        merchantSign = getJsonString("merchantSign");
        senderSign = getJsonString("senderSign");
        serviceInfo = getJsonString("serviceInfo");
        terminalInfo = getJsonString("terminalInfo");
        mac = getJsonString("mac");
        signaturePath = getJsonString("signaturePath");
        transTerminalId = getJsonString("transTerminalId");

        if (2l != roleId && 3l != roleId) {//不存在
            log.warn("我要收款时, 传入参数roleId不存在");
            sendAppErrorMsg("6001", "roleId");
            return null;
        }

        //icCardNum = getJsonString("icCardNum");//IC卡 序号
        icCardYu = getJsonString("icCardYu");//IC卡 域
        encryType = getJsonString("encryType");//IC卡 加密类型

        if (null == clientType) {
            log.warn("我要收款时, 传入参数clientType为空");
            sendAppErrorMsg("6001", "clientType");
            return null;
        }
        if (null == terminalTypeId) {
            log.warn("我要收款时, 传入参数terminalTypeId为空");
            sendAppErrorMsg("6001", "terminalTypeId");
            return null;
        }

        if (null == userId) {
            log.warn("我要收款时, 传入参数userId为空");
            sendAppErrorMsg("6001", "userId");
            return null;
        }

        if (StringUtils.isBlank(functionKey)) {
            log.warn("我要收款时, 传入参数functionKey为空");
            sendAppErrorMsg("6001", "functionKey");
            return null;
        }

        if (StringUtils.isBlank(merchantOrderId)) {
            log.warn("我要收款时, 传入参数merchantOrderId为空");
            sendAppErrorMsg("6001", "merchantOrderId");
            return null;
        }

        if (null == merchantOrderTime) {
            log.warn("我要收款时, 传入参数merchantOrderTime为空");
            sendAppErrorMsg("6001", "merchantOrderTime");
            return null;
        }

        if (null == transAmt) {
            log.warn("我要收款时, 传入参数transAmt为空");
            sendAppErrorMsg("6001", "transAmt");
            return null;
        }

        if (StringUtils.isBlank(accountNumber)) {
            log.warn("我要收款时, 传入参数accountNumber为空");
            sendAppErrorMsg("6001", "accountNumber");
            return null;
        }
        if (StringUtils.isBlank(pin)) {
            log.warn("我要收款时, 传入参数pin为空");
            sendAppErrorMsg("6001", "pin");
            return null;
        }
        if (StringUtils.isBlank(track2Data)) {
            log.warn("我要收款时, 传入参数track2Data为空");
            sendAppErrorMsg("6001", "track2Data");
            return null;
        }

        //判断日期是否是今天
        Date date = new Date();
        String today = DateConvertUtil.dateString(date, "yyyyMMdd");
        if (!merchantOrderTime.startsWith(today)) {
            merchantOrderId = getMerchantOrderId(date, user.getLoginName());
            merchantOrderTime = DateConvertUtil.dateString(date, "yyyyMMddHHmmss");
        }

        //查出商户订单号 是否存在
        TransOrder transOrder = transOrderService.searchOrderByMerchantOrderId(user.getLoginName(), merchantOrderId);
        if (null != transOrder) {
            sendAppErrorMsg("6101", merchantOrderId);
            return null;
        }

        if ("1".equals(encryType)) {
            track2Data = ME30DataDecode.decryptTrace2(track2Data);
            //icCardYu.replace(oldChar, newChar)
        } else if ("2".equals(encryType)) {
            String trackOData = getJsonString("trackOData");
            String[] trackA = ME30DataDecode.decryptTrace2_aic(trackOData, track2Data);
            track2Data = trackA[0];
            track3Data = trackA[1];
        }
        track2Data = track2Data.replaceAll("F", "");//屏蔽二磁道有F的情况

        //组装 发送数据
        Qian4SendLog send = new Qian4SendLog();
        send.setCallType(0);
        send.setUserId(userId);
        send.setOrderTypeId(RECEIVABLES);
        send.setApplication("Purchase.Req");
        send.setTransType("100001");//
        send.setSendTime(date);
        send.setSendSeqId(TimeUtils.getTimeToString());
        send.setTerminalId(terminalId);
        send.setPlatformId(platformId);
        send.setRoleId(roleId);

        send.setMerchantOrderId(merchantOrderId);//商户订单号
        send.setMerchantOrderTime(DateConvertUtil.stringDate(merchantOrderTime, "yyyyMMddHHmmss"));//商户订单号时间
        send.setTransTime(send.getSendTime());
        send.setTransAmt(transAmt);
        send.setCurrency("156");
        send.setAccountNumber(accountNumber);
        send.setPin(pin);
        send.setTrack2Data(track2Data);
        send.setTrack3Data(track3Data);
        //send.setCardholderSign(cardholderSign);//电子签名
        send.setDynamicKeyData(dynamicKeyData);
        send.setMerchantSign(merchantSign);
        send.setSenderSign(senderSign);
        send.setServiceInfo(serviceInfo);
        send.setTerminalInfo(terminalInfo);
        send.setMac(mac);
//        send.setCollectionType(collectionType);
        send.setIp(URLDecoderTools.getRemoteHost(getRequest()));//IP
        send.setIcCardYu(icCardYu);
        send.setCardTypeN(StringUtils.isEmpty(icCardYu) ? 1 : 2);//1 磁条卡 2 IC卡
        send.setTransTerminalId(transTerminalId);

        transOrder = new TransOrder();
        transOrder.setOrderNum(getOrderNumByDate(date));
        transOrder.setOrderTypeId(RECEIVABLES);//我要收款
        transOrder.setUserId(userId);
        transOrder.setPUserId(user.getPUserId());//父用户Id
        transOrder.setTransMoney(Double.parseDouble(transAmt) / 100.0);
//		transOrder.setFeeMoney(fee);//手续费
//		transOrder.setChargeAmount(money-fee);
        transOrder.setRootCategory("账务管理");
        transOrder.setCategory(OrderTypeUtil.RECEIVABLES_STR);
        //transOrder.setName(userName);//收款方
        transOrder.setBankCard(accountNumber);
        //transOrder.setOpeningBank(openingBank);
        transOrder.setObjectiveName(StringUtils.isBlank(user.getCardholder()) ? user.getUserName() : user.getCardholder());//user.getUserName());//对方持卡人姓名
        transOrder.setObjectiveCard(user.getBankCard());//对方银行卡
        transOrder.setObjectiveOpBank(user.getOpeningBank());//对方银行
        transOrder.setStatus(3);//交易状态  0交易失败 1交易成功 2银行交易处理中 3 未付款 4等待对方付款5关闭交易
        transOrder.setClearing(0);//结算状态 0未结算 1结算
        //transOrder.setDescription(description);//交易详情
        transOrder.setCreateDate(date);
        transOrder.setUpdateLongTime(date.getTime());

        //transOrder.setMobile(mobile);//用户 手机号
        transOrder.setObjectiveBBank(user.getBranchesBank());//对方。银行支行
        transOrder.setObjectiveBBProvince(user.getBBankProvince());
        transOrder.setObjectiveBBCity(user.getBBankCity());
        transOrder.setObjectiveMobile(user.getMobile());//对方手机号
        transOrder.setObjectiveBBankCode(user.getBranchesBankCode());//支行Code
        transOrder.setTerminalTypeId(terminalTypeId);
        transOrder.setRoleId(roleId);
        transOrder.setSignaturePath(signaturePath);
        transOrder.setCardTypeN(send.getCardTypeN());//1 磁条卡 2 IC卡
        transOrder.setClientType(clientType);

        Double feeRate = user.getFeeRate();
        if (1 == user.getRoleId().intValue() && 3 == roleId.intValue()) {//全版
            feeRate = user.getFdFeeRate();
        }
        transOrder.setFeeRate(feeRate);//用户费率
        transOrder.setFdMaxFee(user.getFdMaxFee());//用户封顶最高
        transOrder.setFdMinFee(user.getFdMinFee());//用户封顶最低
        transOrder.setTransTerminalId(transTerminalId);

        Object[] resultA = new Object[2];
        resultA[0] = send;
        resultA[1] = transOrder;
        return resultA;
    }

    protected Object[] secondsTOAssembleBean(User user) throws Exception {
        log.debug("--- secondsReceivablesToCard() start ---");
        clientType = Integer.parseInt(getJsonString("clientType"));
        terminalTypeId = Long.parseLong(getJsonString("terminalTypeId"));
        roleId = Long.parseLong(getJsonString("roleId"));

        functionKey = getJsonString("functionKey");
        merchantOrderId = getJsonString("merchantOrderId").substring(0,17).toString();
        merchantOrderTime = getJsonString("merchantOrderTime");
        terminalId = getJsonString("terminalId");
        transAmt = getJsonString("transAmt");
        accountNumber = getJsonString("accountNumber");
        pin = getJsonString("pin");
        track2Data = getJsonString("track2Data");
        track3Data = getJsonString("track3Data");
        cardholderSign = getJsonString("cardholderSign");
        dynamicKeyData = getJsonString("dynamicKeyData");
        merchantSign = getJsonString("merchantSign");
        senderSign = getJsonString("senderSign");
        serviceInfo = getJsonString("serviceInfo");
        terminalInfo = getJsonString("terminalInfo");
        mac = getJsonString("mac");
        signaturePath = getJsonString("signaturePath");
        transTerminalId = getJsonString("transTerminalId");
        functionKey = "SECONDSTO";

        if (1l != roleId && 2l != roleId && 3l != roleId) {//不存在
            log.warn("秒到收款时, 传入参数roleId不存在");
            sendAppErrorMsg("6001", "roleId");
            return null;
        }

        icCardYu = getJsonString("icCardYu");//IC卡 域
        encryType = getJsonString("encryType");//IC卡 加密类型

        if (null == clientType) {
            log.warn("秒到收款时, 传入参数clientType为空");
            sendAppErrorMsg("6001", "clientType");
            return null;
        }
        if (null == terminalTypeId) {
            log.warn("秒到收款时, 传入参数terminalTypeId为空");
            sendAppErrorMsg("6001", "terminalTypeId");
            return null;
        }

        if (null == userId) {
            log.warn("秒到收款时, 传入参数userId为空");
            sendAppErrorMsg("6001", "userId");
            return null;
        }

        if (StringUtils.isBlank(functionKey)) {
            log.warn("秒到收款时, 传入参数functionKey为空");
            sendAppErrorMsg("6001", "functionKey");
            return null;
        }

        if (StringUtils.isBlank(merchantOrderId)) {
            log.warn("秒到收款时, 传入参数merchantOrderId为空");
            sendAppErrorMsg("6001", "merchantOrderId");
            return null;
        }

        if (null == merchantOrderTime) {
            log.warn("秒到收款时, 传入参数merchantOrderTime为空");
            sendAppErrorMsg("6001", "merchantOrderTime");
            return null;
        }

        if (null == transAmt) {
            log.warn("秒到收款时, 传入参数transAmt为空");
            sendAppErrorMsg("6001", "transAmt");
            return null;
        }

        if (StringUtils.isBlank(accountNumber)) {
            log.warn("秒到收款时, 传入参数accountNumber为空");
            sendAppErrorMsg("6001", "accountNumber");
            return null;
        }
        if (StringUtils.isBlank(pin)) {
            log.warn("秒到收款时, 传入参数pin为空");
            sendAppErrorMsg("6001", "pin");
            return null;
        }
        if (StringUtils.isBlank(track2Data)) {
            log.warn("秒到收款时, 传入参数track2Data为空");
            sendAppErrorMsg("6001", "track2Data");
            return null;
        }

        //判断日期是否是今天
        Date date = new Date();
        String today = DateConvertUtil.dateString(date, "yyyyMMdd");
        if (!merchantOrderTime.startsWith(today)) {
            merchantOrderId = getMerchantOrderId(date, user.getLoginName());
            merchantOrderTime = DateConvertUtil.dateString(date, "yyyyMMddHHmmss");
        }

        //查出商户订单号 是否存在
        TransOrder transOrder = transOrderService.searchOrderByMerchantOrderId(user.getLoginName(), merchantOrderId);
        if (null != transOrder) {
            sendAppErrorMsg("6101", merchantOrderId);
            return null;
        }

        if ("1".equals(encryType)) {
            track2Data = ME30DataDecode.decryptTrace2(track2Data);
        } else if ("2".equals(encryType)) {
            String trackOData = getJsonString("trackOData");
            String[] trackA = ME30DataDecode.decryptTrace2_aic(trackOData, track2Data);
            track2Data = trackA[0];
            track3Data = trackA[1];
        }
        track2Data = track2Data.replaceAll("F", "");//屏蔽二磁道有F的情况

        //组装 发送数据
        Qian4SendLog send = new Qian4SendLog();
        send.setCallType(0);
        send.setUserId(userId);
        send.setOrderTypeId(SECONDSTO);
        send.setApplication("Purchase.Req");
        send.setTransType("100001");//
        send.setSendTime(date);
        send.setSendSeqId(TimeUtils.getTimeToString());
        send.setTerminalId(terminalId);
        send.setPlatformId(platformId);
        send.setRoleId(roleId);

        send.setMerchantOrderId(merchantOrderId);//商户订单号
        send.setMerchantOrderTime(DateConvertUtil.stringDate(merchantOrderTime, "yyyyMMddHHmmss"));//商户订单号时间
        send.setTransTime(send.getSendTime());
        send.setTransAmt(transAmt);
        send.setCurrency("156");
        send.setAccountNumber(accountNumber);
        send.setPin(pin);
        send.setTrack2Data(track2Data);
        send.setTrack3Data(track3Data);
        send.setDynamicKeyData(dynamicKeyData);
        send.setMerchantSign(merchantSign);
        send.setSenderSign(senderSign);
        send.setServiceInfo(serviceInfo);
        send.setTerminalInfo(terminalInfo);
        send.setMac(mac);
        send.setIp(URLDecoderTools.getRemoteHost(getRequest()));//IP
        send.setIcCardYu(icCardYu);
        send.setCardTypeN(StringUtils.isEmpty(icCardYu) ? 1 : 2);//1 磁条卡 2 IC卡
        send.setTransTerminalId(transTerminalId);

        transOrder = new TransOrder();
        transOrder.setOrderNum(getOrderNumByDate(date));
        transOrder.setOrderTypeId(SECONDSTO);//秒到收款
        transOrder.setUserId(userId);
        transOrder.setPUserId(user.getPUserId());//父用户Id
        transOrder.setTransMoney(Double.parseDouble(transAmt) / 100.0);

        transOrder.setRootCategory("账务管理");
        transOrder.setCategory(OrderTypeUtil.SECONDSTO_STR);
        transOrder.setBankCard(accountNumber);
        transOrder.setObjectiveName(StringUtils.isBlank(user.getCardholder()) ? user.getUserName() : user.getCardholder());
        transOrder.setObjectiveCard(user.getBankCard());//对方银行卡
        transOrder.setObjectiveOpBank(user.getOpeningBank());//对方银行
        transOrder.setStatus(3);//交易状态  0交易失败 1交易成功 2银行交易处理中 3 未付款 4等待对方付款5关闭交易
        transOrder.setClearing(0);//结算状态 0未结算 1结算
        transOrder.setCreateDate(date);
        transOrder.setUpdateLongTime(date.getTime());

        transOrder.setObjectiveBBank(user.getBranchesBank());//对方。银行支行
        transOrder.setObjectiveBBProvince(user.getBBankProvince());
        transOrder.setObjectiveBBCity(user.getBBankCity());
        transOrder.setObjectiveMobile(user.getMobile());//对方手机号
        transOrder.setObjectiveBBankCode(user.getBranchesBankCode());//支行Code
        transOrder.setTerminalTypeId(terminalTypeId);
        transOrder.setRoleId(roleId);
        transOrder.setSignaturePath(signaturePath);
        transOrder.setCardTypeN(send.getCardTypeN());//1 磁条卡 2 IC卡
        transOrder.setClientType(clientType);

        Double feeRate = user.getFeeRate();
        if (1 == user.getRoleId().intValue() && 3 == roleId.intValue()) {//全版
            feeRate = user.getFdFeeRate();
        }
        transOrder.setFeeRate(feeRate);//用户费率
        transOrder.setFdMaxFee(user.getFdMaxFee());//用户封顶最高
        transOrder.setFdMinFee(user.getFdMinFee());//用户封顶最低
        transOrder.setTransTerminalId(transTerminalId);

        Object[] resultA = new Object[2];
        resultA[0] = send;
        resultA[1] = transOrder;
        return resultA;
    }

    protected Object[] zeroFLPayAssembleBean(User user) throws Exception {
        log.debug("--- zeroFLReceivablesToCard() start ---");
        clientType = Integer.parseInt(getJsonString("clientType"));
        terminalTypeId = Long.parseLong(getJsonString("terminalTypeId"));
        roleId = Long.parseLong(getJsonString("roleId"));

        functionKey = getJsonString("functionKey");
        merchantOrderId = getJsonString("merchantOrderId").substring(0,17).toString();
        merchantOrderTime = getJsonString("merchantOrderTime");
        terminalId = getJsonString("terminalId");
        transAmt = getJsonString("transAmt");
        accountNumber = getJsonString("accountNumber");
        pin = getJsonString("pin");
        track2Data = getJsonString("track2Data");
        track3Data = getJsonString("track3Data");
        cardholderSign = getJsonString("cardholderSign");
        dynamicKeyData = getJsonString("dynamicKeyData");
        merchantSign = getJsonString("merchantSign");
        senderSign = getJsonString("senderSign");
        serviceInfo = getJsonString("serviceInfo");
        terminalInfo = getJsonString("terminalInfo");
        mac = getJsonString("mac");
        signaturePath = getJsonString("signaturePath");
        transTerminalId = getJsonString("transTerminalId");
        functionKey = "ZEROFLPAY";

        if (1l != roleId && 2l != roleId && 3l != roleId) {
            log.warn("零费率收款时, 传入参数roleId不存在");
            sendAppErrorMsg("6001", "roleId");
            return null;
        }

        icCardYu = getJsonString("icCardYu");//IC卡 域
        encryType = getJsonString("encryType");//IC卡 加密类型

        if (null == clientType) {
            log.warn("零费率收款时, 传入参数clientType为空");
            sendAppErrorMsg("6001", "clientType");
            return null;
        }
        if (null == terminalTypeId) {
            log.warn("零费率收款时, 传入参数terminalTypeId为空");
            sendAppErrorMsg("6001", "terminalTypeId");
            return null;
        }

        if (null == userId) {
            log.warn("零费率收款时, 传入参数userId为空");
            sendAppErrorMsg("6001", "userId");
            return null;
        }

        if (StringUtils.isBlank(functionKey)) {
            log.warn("零费率收款时, 传入参数functionKey为空");
            sendAppErrorMsg("6001", "functionKey");
            return null;
        }

        if (StringUtils.isBlank(merchantOrderId)) {
            log.warn("零费率收款时, 传入参数merchantOrderId为空");
            sendAppErrorMsg("6001", "merchantOrderId");
            return null;
        }

        if (null == merchantOrderTime) {
            log.warn("零费率收款时, 传入参数merchantOrderTime为空");
            sendAppErrorMsg("6001", "merchantOrderTime");
            return null;
        }

        if (null == transAmt) {
            log.warn("零费率收款时, 传入参数transAmt为空");
            sendAppErrorMsg("6001", "transAmt");
            return null;
        }

        if (StringUtils.isBlank(accountNumber)) {
            log.warn("零费率收款时, 传入参数accountNumber为空");
            sendAppErrorMsg("6001", "accountNumber");
            return null;
        }
        if (StringUtils.isBlank(pin)) {
            log.warn("零费率收款时, 传入参数pin为空");
            sendAppErrorMsg("6001", "pin");
            return null;
        }
        if (StringUtils.isBlank(track2Data)) {
            log.warn("零费率收款时, 传入参数track2Data为空");
            sendAppErrorMsg("6001", "track2Data");
            return null;
        }

        //判断日期是否是今天
        Date date = new Date();
        String today = DateConvertUtil.dateString(date, "yyyyMMdd");
        if (!merchantOrderTime.startsWith(today)) {
            merchantOrderId = getMerchantOrderId(date, user.getLoginName());
            merchantOrderTime = DateConvertUtil.dateString(date, "yyyyMMddHHmmss");
        }

        //查出商户订单号 是否存在
        TransOrder transOrder = transOrderService.searchOrderByMerchantOrderId(user.getLoginName(), merchantOrderId);
        if (null != transOrder) {
            sendAppErrorMsg("6101", merchantOrderId);
            return null;
        }

        if ("1".equals(encryType)) {
            track2Data = ME30DataDecode.decryptTrace2(track2Data);
            //icCardYu.replace(oldChar, newChar)
        } else if ("2".equals(encryType)) {
            String trackOData = getJsonString("trackOData");
            String[] trackA = ME30DataDecode.decryptTrace2_aic(trackOData, track2Data);
            track2Data = trackA[0];
            track3Data = trackA[1];
        }
        track2Data = track2Data.replaceAll("F", "");//屏蔽二磁道有F的情况

        //组装 发送数据
        Qian4SendLog send = new Qian4SendLog();
        send.setCallType(0);
        send.setUserId(userId);
        send.setOrderTypeId(ZEROFLPAY);
        send.setApplication("Purchase.Req");
        send.setTransType("100001");//
        send.setSendTime(date);
        send.setSendSeqId(TimeUtils.getTimeToString());
        send.setTerminalId(terminalId);
        send.setPlatformId(platformId);
        send.setRoleId(roleId);

        send.setMerchantOrderId(merchantOrderId);//商户订单号
        send.setMerchantOrderTime(DateConvertUtil.stringDate(merchantOrderTime, "yyyyMMddHHmmss"));//商户订单号时间
        send.setTransTime(send.getSendTime());
        send.setTransAmt(transAmt);
        send.setCurrency("156");
        send.setAccountNumber(accountNumber);
        send.setPin(pin);
        send.setTrack2Data(track2Data);
        send.setTrack3Data(track3Data);
        send.setDynamicKeyData(dynamicKeyData);
        send.setMerchantSign(merchantSign);
        send.setSenderSign(senderSign);
        send.setServiceInfo(serviceInfo);
        send.setTerminalInfo(terminalInfo);
        send.setMac(mac);
        send.setIp(URLDecoderTools.getRemoteHost(getRequest()));//IP
        send.setIcCardYu(icCardYu);
        send.setCardTypeN(StringUtils.isEmpty(icCardYu) ? 1 : 2);//1 磁条卡 2 IC卡
        send.setTransTerminalId(transTerminalId);

        transOrder = new TransOrder();
        transOrder.setOrderNum(getOrderNumByDate(date));
        transOrder.setOrderTypeId(ZEROFLPAY);//我要收款
        transOrder.setUserId(userId);
        transOrder.setPUserId(user.getPUserId());//父用户Id
        transOrder.setTransMoney(Double.parseDouble(transAmt) / 100.0);
        transOrder.setRootCategory("账务管理");
        transOrder.setCategory(OrderTypeUtil.ZEROFLPAY_STR);
        transOrder.setBankCard(accountNumber);
        transOrder.setObjectiveName(StringUtils.isBlank(user.getCardholder()) ? user.getUserName() : user.getCardholder());//user.getUserName());//对方持卡人姓名
        transOrder.setObjectiveCard(user.getBankCard());//对方银行卡
        transOrder.setObjectiveOpBank(user.getOpeningBank());//对方银行
        transOrder.setStatus(3);//交易状态  0交易失败 1交易成功 2银行交易处理中 3 未付款 4等待对方付款5关闭交易
        transOrder.setClearing(0);//结算状态 0未结算 1结算
        transOrder.setCreateDate(date);
        transOrder.setUpdateLongTime(date.getTime());

        transOrder.setObjectiveBBank(user.getBranchesBank());//对方。银行支行
        transOrder.setObjectiveBBProvince(user.getBBankProvince());
        transOrder.setObjectiveBBCity(user.getBBankCity());
        transOrder.setObjectiveMobile(user.getMobile());//对方手机号
        transOrder.setObjectiveBBankCode(user.getBranchesBankCode());//支行Code
        transOrder.setTerminalTypeId(terminalTypeId);
        transOrder.setRoleId(roleId);
        transOrder.setSignaturePath(signaturePath);
        transOrder.setCardTypeN(send.getCardTypeN());//1 磁条卡 2 IC卡
        transOrder.setClientType(clientType);

        Double feeRate = 0.0;

        transOrder.setFeeRate(feeRate);//用户费率
        transOrder.setFdMaxFee(user.getFdMaxFee());//用户封顶最高
        transOrder.setFdMinFee(user.getFdMinFee());//用户封顶最低
        transOrder.setTransTerminalId(transTerminalId);

        Object[] resultA = new Object[2];
        resultA[0] = send;
        resultA[1] = transOrder;
        return resultA;
    }

    /**
     * 返回
     *
     * @param pr
     * @param transOrder
     * @param transPriorSettle
     * @param user
     * @param tc
     * @return
     * @throws Exception
     */
    protected Map<String, Object> purchaseResolveResult(Qian4SendLog send, PurchaseResult pr, TransOrder transOrder, TransPriorSettle transPriorSettle, User user, Tchannel tc) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        if (0 == pr.getStatus()) {//错误
            log.debug("我要收款失败");
            result.put("bankResp", "0");
            result.put("reqCode", pr.getReqCode());
            result.put("reqMsg", pr.getReqMsg());
            accountManageQ4Service.receivablesError(transPriorSettle, pr.getReqCode(), pr.getReqMsg());
            qian4SendLogService.updateResCodeMassage(transPriorSettle.getSendId(), pr.getReqCode(), pr.getReqMsg());
//            //推送消息
//            User u =  new User();
//            u.setId(userId);
//            //查询数据库中该用户的极光信息
//            u = userService.searchEntity(u);
//            //苹果手机
//            if(clientType==3){
//                String Status="";
//                if(transPriorSettle.getStatus()==1){
//                    Status="交易成功！";
//                }else if(transPriorSettle.getStatus()==2){
//                    Status="银联处理中!";
//                }else if(transPriorSettle.getStatus()==3){
//                    Status="交易失败!";
//                }
//                //苹果
//                String appKey= JDPushConfig.getAttribute("IOS_JDPush_appKey");
//                String masterSecret=JDPushConfig.getAttribute("IOS_JDPush_masterSecret");
//                Date datetime=new Date();
//                DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                String time=format.format(datetime);
//                //调用方法进行推送消息
//                JdPush.ALERT=userId+"您好！您的中国"+user.getOpeningBank()+"账户\n卡号："+transOrder.getBankCard()+"\n与订单时间"+
//                        time+
//                        "\n进行一笔我要收款操作"+"\n交易金额"+(Double.parseDouble(transAmt) / 100.0)+
//                        "\n交易状态："+Status+"\n终端编号："+transPriorSettle.getTerminalId();
//                JdPush.MSG_CONTENT="交易信息提醒！";
//                JdPush.TITLE="花生米移动支付";
//                JdPush.REGISTRATION_ID=u.getRegistration_id();
//                JdPush.testSendPush(appKey, masterSecret);
//                //安卓手机
//            }else if(clientType==2){
//                String Status="";
//                if(transPriorSettle.getStatus()==1){
//                    Status="交易成功！";
//                }else if(transPriorSettle.getStatus()==2){
//                    Status="银联处理中!";
//                }else if(transPriorSettle.getStatus()==3){
//                    Status="交易失败!";
//                }
//                //安卓
//                String appKey=JDPushConfig.getAttribute("Android_JDPush_appKey");
//                String masterSecret=JDPushConfig.getAttribute("Android_JDPush_masterSecret");
//                Date datetime=new Date();
//                DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                String time=format.format(datetime);
//                //调用方法进行推送消息
//                JdPush.ALERT=userId+"您好！您的中国"+user.getOpeningBank()+"账户\n卡号："+transOrder.getBankCard()+"\n与订单时间"+
//                        time+
//                        "\n进行一笔我要收款操作"+"\n交易金额"+(Double.parseDouble(transAmt) / 100.0)+"\n交易状态："+Status+"\n终端编号："+transPriorSettle.getTerminalId();
//                JdPush.MSG_CONTENT="交易信息提醒！";
//                JdPush.TITLE="花生米移动支付";
//                JdPush.REGISTRATION_ID=u.getRegistration_id();
//                JdPush.testSendPush(appKey, masterSecret);
//            }
        } else {
            transPriorSettle = accountManageQ4Service.purchaseResolveResult(transPriorSettle, send, pr, tc, user.getOrganizationId());
            String cParam = terminalTypeId + "_" + transPriorSettle.getId();
            String cParamB64 = new String(Des3.encodeXP(cParam));

            result.put("bankResp", "1");
            result.put("category", transOrder.getCategory());
            result.put("status", transOrder.getStatus());
            result.put("orderNum", transOrder.getOrderNum());
            result.put("transTime", DateConvertUtil.dateString(transOrder.getCreateDate(), "HH:mm:ss"));
            //result.put("certificateUrl",Certificate+terminalTypeId+"_"+transPriorSettle.getId()+".jsp");
            result.put("certificateUrl", Certificate + cParamB64);

            String acquirersName = user.getOpeningBank();
            if (null != acquirersName) {
                acquirersName = acquirersName.replace("中国", "");
            }
//			String acquirersName = "交通银行";
            result.put("merchantName", MERCHANT_NAME);//商户名称
            result.put("merchantId", MERCHANT_ID);//商户编号
            result.put("terminalId", transPriorSettle.getTerminalId());//终端编号
            result.put("acquirersName", null != acquirersName ? acquirersName : transPriorSettle.getAcquirersName());//收单行
            result.put("issueBank", null == transPriorSettle.getIssueBank() ? "" : transPriorSettle.getIssueBank());//发卡行
            result.put("bankCard", transOrder.getBankCard());//收款卡号
            result.put("cardType", null == transPriorSettle.getCardType() ? "" : transPriorSettle.getCardType());//收款卡号
            result.put("expireDate", null == transPriorSettle.getExpireDate() ? "" : transPriorSettle.getExpireDate());//卡有效期（预授权时）
            result.put("batchId", null == transPriorSettle.getBatchId() ? "" : transPriorSettle.getBatchId());//批次号
            result.put("authorizationCode", null == transPriorSettle.getAuthorizationCode() ? "" : transPriorSettle.getAuthorizationCode());//授权码
            result.put("bankTransTime", DateConvertUtil.dateString(transOrder.getCreateDate(), "yyyy/MM/dd"));//日期/时间  transPriorSettle.getBankTransTime()
            result.put("transMoney", transOrder.getTransMoney());//交易金额
            result.put("bankRef", transPriorSettle.getBankRef());//参考号
            result.put("searchId", transPriorSettle.getSearchId());//凭证号
            result.put("transId", transPriorSettle.getBankOrderNum());//凭证号
            result.put("receivablesId", transPriorSettle.getId());//凭证号

            result.put("reqCode", transPriorSettle.getResponseCode());
            if (StringUtils.isNotBlank(transPriorSettle.getBankMessage()))
                result.put("reqMsg", transPriorSettle.getBankMessage());
            //log.debug("我要收款时, 收款成功！");
            //qian4SendLogService.updateResCodeMassage(transPriorSettle.getSendId(), transPriorSettle.getResponseCode(), transPriorSettle.getBankMessage());

            result.put("merchantOrderId", transPriorSettle.getMerchantOrderId());
            //推送消息
//            User u =  new User();
//            u.setId(userId);
//            //查询数据库中该用户的极光信息
//            u = userService.searchEntity(u);
//            //苹果手机
//            if(clientType==3){
//                String Status="";
//                if(transPriorSettle.getStatus()==1){
//                    Status="交易成功！";
//                }else if(transPriorSettle.getStatus()==2){
//                    Status="银联处理中!";
//                }else if(transPriorSettle.getStatus()==3){
//                    Status="交易失败!";
//                }
//                //苹果
//                String appKey= JDPushConfig.getAttribute("IOS_JDPush_appKey");
//                String masterSecret=JDPushConfig.getAttribute("IOS_JDPush_masterSecret");
//                Date datetime=new Date();
//                DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                String time=format.format(datetime);
//                //调用方法进行推送消息
//                JdPush.ALERT=userId+"您好！您的中国"+acquirersName+"账户\n卡号："+transOrder.getBankCard()+"\n与订单时间"+
//                        time+
//                        "\n进行一笔我要收款操作"+"\n交易金额"+(Double.parseDouble(transAmt) / 100.0)+"\n交易状态："+Status+
//                        "\n终端编号："+transPriorSettle.getTerminalId();
//                JdPush.MSG_CONTENT="交易信息提醒！";
//                JdPush.TITLE="花生米移动支付";
//                JdPush.REGISTRATION_ID=u.getRegistration_id();
//                JdPush.testSendPush(appKey, masterSecret);
//                //安卓手机
//            }else if(clientType==2){
//                String Status="";
//                if(transPriorSettle.getStatus()==1){
//                    Status="交易成功！";
//                }else if(transPriorSettle.getStatus()==2){
//                    Status="银联处理中!";
//                }else if(transPriorSettle.getStatus()==3){
//                    Status="交易失败!";
//                }
//                //安卓
//                String appKey=JDPushConfig.getAttribute("Android_JDPush_appKey");
//                String masterSecret=JDPushConfig.getAttribute("Android_JDPush_masterSecret");
//                Date datetime=new Date();
//                DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                String time=format.format(datetime);
//                //调用方法进行推送消息
//                JdPush.ALERT=userId+"您好！您的中国"+acquirersName+"账户\n卡号："+transOrder.getBankCard()+"\n与订单时间"+
//                        time+
//                        "\n进行一笔我要收款操作"+"\n交易金额"+(Double.parseDouble(transAmt) / 100.0)+"\n交易状态："+Status+"\n终端编号："+transPriorSettle.getTerminalId();
//                JdPush.MSG_CONTENT="交易信息提醒！";
//                JdPush.TITLE="花生米移动支付";
//                JdPush.REGISTRATION_ID=u.getRegistration_id();
//                JdPush.testSendPush(appKey, masterSecret);
//            }
        }
        return result;
    }

    /**
     * 撤销超时
     *
     * @return
     * @throws Exception
     */
    public Map<String, Object> revocationOrderTimeOut(Qian4SendLog recSend, TransPriorSettle transPriorSettle) throws Exception {

        Date date = new Date();
        Qian4SendLog send = new Qian4SendLog();
        send.setCallType(0);
        send.setUserId(recSend.getUserId());
        send.setApplication("Void.Req");
        send.setOrderTypeId(OrderTypeUtil.REVOCATION);
        send.setSendTime(date);
        send.setRoleId(recSend.getRoleId());
        send.setSendSeqId(TimeUtils.getTimeToString());
        send.setMerchantId(recSend.getMerchantId());//商户代码 ##
        send.setTerminalId(recSend.getTerminalId());
        send.setPlatformId(recSend.getPlatformId());//平台ID  ##
        send.setTransType("200000");//200000：撤销

        send.setMerchantOrderId(DateConvertUtil.dateString(date, "yyyyMMddHHmmssSSS"));
        send.setMerchantOrderTime(DateConvertUtil.stringDate(merchantOrderTime, "yyyyMMddHHmmss"));
        send.setTransTime(send.getSendTime());
        send.setOrgTransId(recSend.getBankOrderNum());//原订单号
        send.setOrgTransTime(recSend.getMerchantOrderTime());//原订单时间
        send.setOrgMerchantOrderId(recSend.getMerchantOrderId());
        send.setTransAmt(recSend.getTransAmt());

        send.setAccountNumber(recSend.getAccountNumber());//卡号  安心一百 需要
        send.setTrack2Data(recSend.getTrack2Data());
        send.setTrack3Data(recSend.getTrack3Data());
        send.setPin(recSend.getPin());

        send.setMerchantSign(recSend.getMerchantSign());
        send.setSenderSign(recSend.getSenderSign());
        send.setServiceInfo(recSend.getServiceInfo());
        send.setTerminalInfo(recSend.getTerminalInfo());
        //send.setMac(mac);

        //8583 需要传入
        send.setBankRef(recSend.getBankRef());
        send.setCollectionType(recSend.getCollectionType());
        send.setBankOrderNum(recSend.getBankOrderNum());
        send.setBatchId(recSend.getBatchId());
        send.setAuthorizationCode(recSend.getAuthorizationCode());
        send.setResponseCode(recSend.getResponseCode());
        send.setIcCardYu(recSend.getIcCardYu());//IC卡域
        //send.setIccParam(new ICCardParam());

        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("status", 0);
        try {
            resultMap = accountManageQ4Service.isCanRevocationOrder(send);
            int status = (Integer) resultMap.get("status");
            if (status == 1) {
                TransOrder transOrder = new TransOrder();
                transOrder.setOrderNum(transPriorSettle.getOrderNum());
                transOrder = transOrderService.searchEntity(transOrder);
                if (transOrder.getStatus().intValue() == 1) {
                    if (null != transPriorSettle.getStatus() && 1 == transPriorSettle.getStatus().intValue()) {
                        //查询订单 修改金额
                        accountManageQ4Service.updateUserMoney(transOrder, 0, transOrder.getChargeAmount());
                    }
                }
                //修改订单状态 为已撤销 作为一个事务提交  暂时用同步的方式
                transOrderService.updateStatusClearing(transPriorSettle.getOrderNum(), 7, null);//发起撤销

                transPriorSettle = transPriorSettleService.searchTransPriorSettle(send.getTerminalId(), send.getOrgMerchantOrderId());
                date = new Date();
                send.setMerchantOrderId(DateConvertUtil.dateString(date, "yyyyMMddHHmmssSSS"));
                send.setMerchantOrderTime(date);
                //添加 日志   在调用上海接口时  保证有一条撤销记录
                long sendId = qian4SendLogService.insertEntity(send);
                send.setId(sendId);
                //真正去冲正的方法
                resultMap = accountManageQ4Service.revocationOrder(send);
                int flag = (Integer) resultMap.get("status");
                if (flag == 0 && (send.timeOut == 1 || send.timeOut == 2 || send.timeOut == 3)) {
                    resultMap = revocationOrderTimeOut(recSend, transPriorSettle);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }
}
